import { CanActivate, ExecutionContext, ForbiddenException, Inject, Injectable, UnauthorizedException } from "@nestjs/common";
import { Observable } from "rxjs";
import { ConfigService } from "@nestjs/config"
import { JwtService } from '@nestjs/jwt';
import { UserService } from "../user/user.service";
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private configService: ConfigService,
    private jwtService: JwtService,
    private userService: UserService,
  ) { }

  // @Inject()
  // userService: UserService;
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const whiteList = ["/auth/login", "/register", "/auth/refreshToken"];
    // console.log(request);

    const isW = whiteList.some((item) => {
      return request.url.includes(item)
    })

    const getClass = context.getClass();
    const getHandler = context.getHandler();
    console.log(getClass.name);
    console.log(getHandler.name);

    if (isW) {
      return request;
    }

    try {
      // console.log("开始验证token");

      const token = request.headers.authorization;
      // console.log(token);

      // 密钥
      // const JWT_SECRET = this.configService.get("JWT_SECRET")
      // console.log(JWT_SECRET);

      // 解析token
      const user = this.jwtService.verify(token)

      const res = this.userService.findUserPermission(user.id)

      // const permissionList = []
      // const permission = res.roles.forEach((role: any) => {
      //   role.menu.forEach((menu: any) => {
      //     menu.permission.forEach(per => {
      //       permissionList.push(per)
      //     })
      //   })
      // })
      // const perUrlList = permissionList.map((item) => {
      //   return item.path
      // })
      // // console.log(perUrlList);
      // // console.log(request.url);
      // const isPer = perUrlList.includes(request.url)
      // console.log(isPer);
      // if (isPer) {
      //   // return true
      // } else {
      //   Promise.resolve(new ForbiddenException({
      //     cause: null,
      //     description: "你没有权限访问",
      //   }));
      // }

      // console.log(11,user);
      const Method = request.method
      if (Method === "GET") {
        request.query.userId = user.id
      } else {
        request.body.userId = user.id
      }
    } catch (error) {
      Promise.resolve(new ForbiddenException({
        cause: error,
        description: "你没有权限访问",
      }));
    }
    return Promise.resolve(true)
  }
}